<?php
namespace Common\Model;
use Think\Model;
class CustExtModel extends Model {
	protected $connection = 'DB_BASE_DSN';
	protected $tableName = 'qyx_cust_ext'; 
	
	
	public function saveCustExt($data){
		$map['custid'] = $data['custid'];
		$result = $this->where($map)->find();
		if(empty($result)){
			$result = $this->add($data);
		}else{
			$data['updatetime'] = date("Y-m-d H:i:s");
			$result = $this->where($map)->save($data);
		}
		
		if($result){
			return $data['custid'];
		}else{
			return false;
		}
	}
	
	
	public function getCustExtInfoById($custid , $map = array()){
		$map['custid'] = $custid;
		$result = $this->where($map)->find();
		if(empty($result)) $result = array();
		return $result;
	}
	
	
	
	public function getKitchenerCustList($data){
		$map = array();
		if(!empty($data['area']) && !empty($data['area'])){
			$map['qyx_cust.area']  = array('like','%'.$data['area'].'%');
		}
	
		if(!empty($data['custtype'])){
			$map['qyx_cust.custtype']  = $data['custtype'];
		}
		
		if(!empty($data['iskitchener'])){
			$map['qyx_cust_ext.iskitchener']  = 1;
		}
		
		if(!empty($data['exclude'])){
			$map['qyx_cust.custid']  = array('NOT IN',$data['exclude']);
		}
	
		$total = $this->join('left join qyx_cust on qyx_cust_ext.custid=qyx_cust.custid')->where($map)->count();
		$total = (int)$total;
		$fields = array('qyx_cust.custid','qyx_cust.nickname','qyx_cust.realname','qyx_cust.updatetime',
				'qyx_cust.status','qyx_cust.sex','qyx_cust.age','qyx_cust.area','qyx_cust_ext.*');
	
		if(empty($data['sortField']))$data['sortField'] = "qyx_cust_ext.custid";
		if(empty($data['sortOrder']))$data['sortOrder'] = "desc";
	
		if(empty($data['pageSize']) && empty($data['pageIndex']))
			$result = $this->join('left join qyx_cust on qyx_cust_ext.custid=qyx_cust.custid')->field($fields)->where($map)->order("{$data['sortField']} {$data['sortOrder']}")->select();
		else
			$result = $this->join('left join qyx_cust on qyx_cust_ext.custid=qyx_cust.custid')->field($fields)->where($map)->order("{$data['sortField']} {$data['sortOrder']}")->limit($data['pageIndex']*$data['pageSize'] , $data['pageSize'])->select();
	
		if(empty($result)) $result = array();
	
		$pages = ($total==0) ? 0 : (!empty($data['pageSize']) ? ceil($total/$data['pageSize']) : 1);
	
		return array('total'=>$total , 'data'=>$result , 'pages'=>$pages);
	}
	
	
	public function getKitchenerCustById($custid){
		$map['qyx_cust.custid'] = $custid;
		$fields = array('qyx_cust.custid','qyx_cust.nickname','qyx_cust.realname','qyx_cust.updatetime',
				'qyx_cust.status','qyx_cust.sex','qyx_cust.age','qyx_cust.area','qyx_cust_ext.*');
		$result = $this->join('left join qyx_cust on qyx_cust_ext.custid=qyx_cust.custid')->field($fields)->where($map)->find();
		if(empty($result)) $result = array();
		return $result;
	}
}


